package com.ctshk.sapp.system.controller;

import com.ctshk.common.annotations.OperationLogAnnotation;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.OperationLogModel;
import com.ctshk.common.enums.OperationLogType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.web.support.BaseController;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.AddSysUserReq;
import com.ctshk.rpc.system.req.ImageUrlStr;
import com.ctshk.rpc.system.req.QuerySysUserReq;
import com.ctshk.rpc.system.req.UpdateMyInfoReq;
import com.ctshk.rpc.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Api(value = "用户", tags = "用户管理")
@RestController
@RequestMapping("/account")
public class SysUserController extends BaseController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @DubboReference
    private ISysUserService sysUserService;

    @ApiOperation(value = "创建用户", notes = "创建系统用户")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.ADD, operTitle = "创建用户", operDesc = "创建系统用户")
    @PostMapping("/add")
    public Result add(@RequestBody @Valid AddSysUserReq addSysUserReq) {
        try {
            long l = sysUserService.addUser(addSysUserReq, super.getCurrentUser(getRequest()).getId());
            return Result.success(l);
        } catch (Exception e) {
            String msg = e.getMessage();
            if (e.getMessage().contains("uk_email")) {
                // 违反唯一主键uk_email
                msg = "该邮箱已被使用！";
            } else if (e.getMessage().contains("uk_login_name")) {
                // 违反唯一主键 uk_login_name
                msg = "该用户名已被使用！";
            } else if (e.getMessage().contains("uk_employee_number")) {
                // 违反唯一主键 uk_employee_number
                msg = "该员工编号已被使用！";
            }
            return Result.failed(SystemError.SCENIC_5019, msg);
        }
    }

    @ApiOperation(value = "删除用户", notes = "删除系统用户")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.DELETE, operTitle = "删除用户", operDesc = "删除系统用户")
    @GetMapping("/del/{id}")
    public Result add(@PathVariable long id) {
        return Result.success(sysUserService.del(id, super.getCurrentUser(getRequest()).getId()));
    }

    @ApiOperation(value = "修改用户", notes = "修改系统用户")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.UPDATE, operTitle = "修改用户", operDesc = "修改系统用户")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid AddSysUserReq addSysUserReq) {
        return Result.success(sysUserService.update(addSysUserReq, super.getCurrentUser(getRequest()).getId()));
    }

    @ApiOperation(value = "用户详情", notes = "查询指定用户详情")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.QUERY, operTitle = "查询用户", operDesc = "查询指定用户")
    @GetMapping("/info/{param}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "param", value = "用户id或昵称"),
            @ApiImplicitParam(name = "queryType", value = "查询类型,1=id查询;2=昵称查询")
    })
    public Result<UserDTO> info(@PathVariable Object param, @RequestParam Integer queryType) {
        return Result.success(sysUserService.loadUserByParam(param, queryType));
    }

    @ApiOperation(value = "我的信息", notes = "获取当前登录用户的信息")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.QUERY, operTitle = "我的信息", operDesc = "获取当前登录用户的信息")
    @GetMapping("/currentUserInfo")
    public Result<UserDTO> currentUserInfo() {

        UserDTO userDTO = sysUserService.loadUserByParam(getCurrentUser(getRequest()).getId(), 1);
        return Result.success(userDTO);
    }

    @ApiOperation(value = "修改我的信息", notes = "修改我的信息")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.UPDATE, operTitle = "修改我的信息", operDesc = "修改我的信息")
    @PostMapping("/updateMyInfo")
    public Result updateMyInfo(@RequestBody @Valid UpdateMyInfoReq req) {
        sysUserService.updateMyInfo(req, super.getCurrentUser(getRequest()).getId());
        return Result.success();
    }

    @ApiOperation(value = "修改头像", notes = "修改当前登录用户的头像")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.UPDATE, operTitle = "修改头像", operDesc = "修改当前登录用户的头像")
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestBody @Valid ImageUrlStr avatar) {
        sysUserService.updateAvatar(avatar.getAvatar(), super.getCurrentUser(getRequest()).getId());
        return Result.success();
    }


    @ApiOperation(value = "用户列表", notes = "分页查询用户列表")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.QUERY, operTitle = "查询用户列表", operDesc = "分页查询用户列表")
    @PostMapping("/list")
    public Result<PageResponse<UserDTO>> list(@RequestBody QuerySysUserReq querySysUserReq) {
        return Result.success(sysUserService.listUser(querySysUserReq, getCurrentUser(getRequest())));
    }

    @ApiOperation(value = "账号启用禁用", notes = "账号启用禁用")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.UPDATE, operTitle = "账号启用禁用", operDesc = "账号启用禁用")
    @GetMapping("/disabled/{uid}")
    public Result disabled(@PathVariable long uid) {
        UserDTO userDTO = sysUserService.loadUserByParam(uid, 1);
        AddSysUserReq addSysUserReq = new AddSysUserReq();
        addSysUserReq.setId(uid);
        addSysUserReq.setStatus(userDTO.getStatus() == 0 ? 1 : 0);
        sysUserService.update(addSysUserReq, super.getCurrentUser(getRequest()).getId());
        return Result.success();
    }

    @ApiOperation(value = "账号解锁", notes = "账号解锁")
    @OperationLogAnnotation(operModul = OperationLogModel.USER, operType = OperationLogType.UPDATE, operTitle = "账号解锁", operDesc = "账号解锁")
    @GetMapping("/unlock/{uid}")
    public Result unlock(@PathVariable long uid) {
        UserDTO userDTO = sysUserService.loadUserInfo(uid, 1);
        String lockoutKey = RedisConstants.ACCOUNT_LOCKOUT + uid;
        String lockCountKey = RedisConstants.ACCOUNT_LOCKOUT_TIMES + userDTO.getUsername();
        if (redisTemplate.hasKey(lockoutKey)) {
            redisTemplate.delete(lockoutKey);//有值就解锁
        }
        if (redisTemplate.hasKey(lockCountKey)) {
            redisTemplate.delete(lockCountKey);//有值就删除锁定次数
        }
        return Result.success();
    }

}
